﻿using System;
using System.Windows.Input;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Unity;
using Hopscotch.Presentation.Common;
using Hopscotch.Presentation.Common.Threading;


namespace Hopscotch.Application.Shell.Commands
{
    public class LoadToolCommand : ICommand
    {
        private readonly IUnityContainer container;
        private readonly IRegionManager regionManager;
        private readonly IShellContext workspaceContext;
        private readonly IDispatcher dispatcher;

        public event EventHandler CanExecuteChanged
        {
            add { }
            remove { }
        }

        public LoadToolCommand(
            IUnityContainer container,
            IRegionManager regionManager,
            IShellContext workspaceContext,
            IDispatcher dispatcher)
        {
            this.container = container;
            this.regionManager = regionManager;
            this.workspaceContext = workspaceContext;
            this.dispatcher = dispatcher;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            Type viewType = parameter as Type;
            if (viewType != null)
            {
                using (var childContainer = container.CreateChildContainer())
                {
                    //Scope the workspace context.
                    childContainer.RegisterInstance<IShellContext>(workspaceContext);
                    childContainer.RegisterInstance<IDispatcher>(dispatcher);

                    var view = childContainer.Resolve(viewType);

                    this.regionManager.AddToRegion(RegionNames.WorkspaceRegion, view);
                }
            }
        }

    }
}
